package com.gxuwz.stats.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.mapper.UserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

public class UserDataListener extends AnalysisEventListener<User> {

    private final List<User> users;
    private final UserMapper userMapper;
    private final boolean updateSupport;

    public UserDataListener(List<User> users, UserMapper userMapper, boolean updateSupport) {
        this.users = users;
        this.userMapper = userMapper;
        this.updateSupport = updateSupport;
    }
    @Override
    public void invoke(User user, AnalysisContext context) {
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        }
        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("普通用户");
        }
// 检查是否需要更新已存在的用户
        User existingUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (existingUser != null) {
            if (updateSupport) {
                // 更新现有用户数据
                existingUser.setRole(user.getRole());
                existingUser.setDegree(user.getDegree());
                existingUser.setPosition(user.getPosition());
                existingUser.setPost(user.getPost());
                existingUser.setDepartment(user.getDepartment());
                userMapper.updateById(existingUser);
                users.add(existingUser);
            }
        } else {
            // 插入新用户数据
            userMapper.insert(user);
            users.add(user);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 数据解析完成后执行的操作
    }
}

